package com.sushi.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import lombok.extern.slf4j.Slf4j;

/**
 * 图片工具类
 * @author Administrator
 */
@Slf4j
public class FileUtil {

    public static final String PDF = "pdf";
    public static final String TXT = "txt";
    public static final String MP3 = "mp4";
    public static final String MP4 = "mp3";
    public static final String MKV = "mkv";
    public static final String GIF = "gif";
    public static final String DEFAULT_TEMP_FILE_DIR = "D:/Temp/";


    /**
     * 下载文件到本地 直接下载到默认目录 (默认解析文件名)
     * 使用前需要设置默认路径，否则可能会下载失败
     * @param targetFileUrl 要下载的文件路径 http....
     * @return 返回下载后的文件对象
     */
    public synchronized static File downloadFile(String targetFileUrl) {
        return downloadFile(targetFileUrl, DEFAULT_TEMP_FILE_DIR);
    }

    /**
     * 下载文件到本地 定义下载后的文件名，格式从默认url取
     * @param targetFileUrl 要下载的文件路径 http....
     * @param targetLocalDir 存放文件的目录，末尾不带/
     * @param localFileName 自定义文件名
     * @return 返回下载后的文件对象
     */
    public synchronized static File downloadFile(String targetFileUrl, String targetLocalDir, String localFileName) {
        String fileFullName = targetFileUrl.substring(targetFileUrl.lastIndexOf("/") + 1);
        String[] split = fileFullName.split(StringUtil.DIR_POINT);
        if (split.length < 2) {
            log.info("文件名解析错误");
            return null;
        }
        if (StringUtil.isNotBlank(localFileName)) {
            return downloadFile(targetFileUrl, targetLocalDir, localFileName, split[1]);
        }
        return downloadFile(targetFileUrl, targetLocalDir, split[0], split[1]);
    }

    /**
     * 下载文件到本地 自动解析文件名
     * @param targetFileUrl 要下载的文件路径 http....
     * @param targetLocalDir 存放文件的目录，末尾不带/
     * @return 返回下载后的文件对象
     */
    public synchronized static File downloadFile(String targetFileUrl, String targetLocalDir) {
        return downloadFile(targetFileUrl, targetLocalDir, null);
    }

    /**
     * 下载文件到本地
     * @param targetFileUrl 要下载的文件路径 http....
     * @param targetLocalDir 存放文件的目录，末尾不带/
     * @param localFileName 自定义文件名
     * @param localFileType 自定义存放本地的文件类型
     * @return 返回下载后的文件对象
     */
    @SuppressWarnings("finally")
    public synchronized static File downloadFile(String targetFileUrl, String targetLocalDir, String localFileName, String localFileType) {
        File file = null;
        try {
            URL url = new URL(targetFileUrl);
            URLConnection urlConnection = url.openConnection();
            HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
            httpUrlConnection.setConnectTimeout(1000 * 5);
            httpUrlConnection.setRequestMethod("GET");
            httpUrlConnection.setRequestProperty("Charset", "UTF-8");
            httpUrlConnection.connect();
            int fileSize = httpUrlConnection.getContentLength();
            log.info("即将下载文件，大小为：{}", fileSize / (1024 * 1024) + "MB");
            BufferedInputStream bufferedInputStream = new BufferedInputStream(httpUrlConnection.getInputStream());
            String localFileFullName = localFileName + "." + localFileType;
            String localDir = targetLocalDir + File.separatorChar + localFileFullName;
            file = new File(localDir);
            if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            int size;
            byte[] buf = new byte[2048];
            while ((size = bufferedInputStream.read(buf)) != -1) {
                fileOutputStream.write(buf, 0, size);
            }
            bufferedInputStream.close();
            fileOutputStream.close();
            log.info("文件下载成功，请查收");
        }catch (MalformedURLException e) {
            log.info("url格式错误，文件下载失败");
        }catch (IOException e) {
            log.info("连接异常，文件下载失败");
        }finally {
            return file;
        }
    }




}
